<?php

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Config;
use think\Db;
use think\Request;

class Evaluation extends Controller
{

    use \app\admin\traits\controller\Controller; // 复用代码

    /**
     *  评价管理列表,是以司机为单位
     * @author 邓汉炜
     * @url /admin/evaluation/index
     */
    public function index()
    {
        $data = input();
        $url = '/admin/evaluation/index_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'all';
        } else {
            $searchData['search'] = 'all';
        }
        if ($this::$isdelete){
            $map['d.isdelete'] = 1;
            $map['au.isdelete'] = 1;
        }else{
            $map['d.isdelete'] = 0;
            $map['au.isdelete'] = 0;
        }
        // 司机姓名
        if($data['realname']){
            $map['au.realname'] = ['like',"%{$data['realname']}%"];
        }
        // 司机手机号码
        if($data['mobile']){
            $map['au.mobile'] = ['like',"%{$data['mobile']}%"];
        }
        // 司机身份证
        if($data['id_card']){
            $map['d.id_card'] = ['like',"%{$data['id_card']}%"];
        }
        // 司机车牌号
        if($data['plate_number']){
            $map['d.plate_number'] = ['like',"%{$data['plate_number']}%"];
        }
        // 司机车牌号
        if($data['plate_number']){
            $map['d.plate_number'] = ['like',"%{$data['plate_number']}%"];
        }
        if ($data['title']){
            $driverUserIds = Db::name('dispatch_traveler_group')->where('title','like',"%{$data['title']}%")->column('driver_user_id');
            $driverUserIds = array_unique($driverUserIds); // 获取数组中唯一的用户id
            if (!empty($driverUserIds)){
                $map['au.id'] = ['in', $driverUserIds];
            }
            unset($driverUserIds);
        }
        // 出发时间
        if (!empty($data['date1']) && !empty($data['date2'])){
            $date = [];
            if ($data['date1'] < $data['date2']){
                $date = [$data['date1'], $data['date2']];
            }else{
                $date = [$data['date2'], $data['date1']];
            }
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date','between time',$date)
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }elseif (!empty($data['date1'])){
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date',strtotime($data['date1']))
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }elseif (!empty($data['date2'])){
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date',strtotime($data['date2']))
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }
        if (!empty($map['au.id']) && !empty($driverUserIds)){
            foreach ($map['au.id'][1] as $index10 => $item10) {
                if (!in_array($item10,$driverUserIds)){
                    unset($map['au.id'][1][$index10]);
                }
            }
        }elseif(!empty($driverUserIds)){
            if ($driverUserIds == 1){
                $map['au.id'] = 0;
            }else{
                $map['au.id'] = ['in', $driverUserIds];
            }
        }
        $listRows = $this->request->param('numPerPage') ? 20 : Config::get('paginate.list_rows');
        $list = Db::name('driver')
            ->alias("d")
            ->join("tp_admin_user au","au.id=d.user_id","left")
            ->where($map)
            ->order('d.id','desc')
            ->field('d.*')
            ->paginate($listRows, false,  ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];
        $dispatchData = []; // 派单数据
        if ($listData){
            foreach ($listData as $index => $listDatum) {
                // 根据司机的用户id在分配单里查找已结算的派单
                $dispatchOrder = Db::name('dispatch_traveler_group')
                    ->where('driver_user_id',$listDatum['user_id'])
                    ->where('dispatch_group_status','accounts')
                    ->order('id','desc')
                    ->select();
                static $totalOrders = 0; // 总订单数量
                static $totalGoods = 0; // 总好评数量
                static $totalBads = 0; // 总差评数量
                static $totalnotEvaluated = 0; // 总未平价订单
                if ($dispatchOrder){
                    // 获取派单下的总好评数,订单总数,差评数,未评价,好评率
                    foreach ($dispatchOrder as $index01 => $item) {
                        // 普通订单与接送机订单 is_pick_up 为1 时是接送机订单
                        $commonOrder = $this->getCommonOrder($item['id']);
                        $dispatchOrder[$index01]['good'] = $commonOrder['good'];
                        $dispatchOrder[$index01]['bad'] = $commonOrder['bad'];
                        $dispatchOrder[$index01]['noEvaluation'] = $commonOrder['noEvaluation'];
                        $dispatchOrder[$index01]['totalOrder'] = $commonOrder['totalOrder'];
                        $dispatchOrder[$index01]['feedBack'] = empty($commonOrder['feedBack'])? 0:$commonOrder['feedBack'].'%';
                        $totalGoods += $commonOrder['good'];
                        $totalBads += $commonOrder['bad'];
                        $totalnotEvaluated += $commonOrder['noEvaluation'];
                        $totalOrders += $commonOrder['totalOrder'];
                    }
                    $dispatchData[$listDatum['id']] = $dispatchOrder;
                }
                $listData[$index]['totalGoods'] = $totalGoods;
                $listData[$index]['totalBads'] = $totalBads;
                $listData[$index]['totalnotEvaluated'] = $totalnotEvaluated;
                $listData[$index]['totalOrders'] = $totalOrders;
                if (!empty($totalGoods) || !empty($totalBads) || !empty($totalnotEvaluated)){
                    $feedBack = round($totalGoods/($totalGoods+$totalBads+$totalnotEvaluated)*100, 2);
                } else {
                    $feedBack = 0;
                }
                $listData[$index]['totalFeedBack'] = empty($feedBack) ? 0:$feedBack.'%';
                $totalOrders = 0; // 总订单数量
                $totalGoods = 0; // 总好评数量
                $totalBads = 0; // 总差评数量
                $totalnotEvaluated = 0; // 总未平价订单
            }
        }
        $page = $list->render();
        $count = $list->total();
        $this->view->assign('count',$count);
        $this->view->assign('searchCondition', $searchData);
        $this->view->assign('page',$page);
        $this->view->assign('list',$list);
        $this->view->assign('listData', $listData);
        $this->view->assign('dispatchData', $dispatchData);
        return $this->view->fetch();
    }

    /**
     *  获取订单下的点评信息
     * @author 邓汉炜
     */
    public function getCommonOrder($groupId = null)
    {
        if (!empty($groupId) && is_numeric($groupId)){
            // 从订单表获取订单id
            $oids = Db::name('order_traveler')->where('group_id',$groupId)->column('oid');
            if (empty($oids)){
                // 接送机订单  分组id去找派单id，派单id再去找订单id
                $dispatchId = Db::name('dispatch_traveler_group')->where('id',$groupId)->value('dispatch_id');
                $oids = Db::name('dispatch_order')->where('dispatch_id',$dispatchId)->column('oid');
            }
            $oids = array_unique($oids);
            // 获取所有订单
            $oidData = Db::name('order')->where('id','in',$oids)->select();
            static $good = 0; // 好评
            static $bad = 0; // 差评
            static $noEvaluation = 0; // 未评价
            $totalOrder = count($oidData); // 一个派单的订单总数
            if ($oidData) {
                foreach ($oidData as $index => $oidDatum) {
                    switch ($oidDatum['is_review']){
                        case 0: $noEvaluation++; break;
                        case 1: $good++; break;
                        case 2: $bad++; break;
                        default: $noEvaluation++;
                    }
                }
            }
            if (!empty($good) || !empty($bad) || !empty($noEvaluation)){
                $feedBack = round($good/($good+$bad+$noEvaluation)*100, 2);
            } else {
                $feedBack = 0;
            }
            $msg['good'] = $good;
            $msg['bad'] = $bad;
            $msg['noEvaluation'] = $noEvaluation;
            $msg['totalOrder'] = $totalOrder;
            $msg['feedBack'] = $feedBack;
            $good = 0;
            $bad = 0;
            $noEvaluation = 0;
            return $msg;
        } else {
            return '非法参数';
        }
    }

    /**
     *  订单评价详细情况
     * @description 司机的趟数上的趟数明细
     * @author 邓汉炜
     * @url /admin/evaluation/orderEvaluationDetails
     */
    public function orderEvaluationDetails()
    {
        $data = input();
        $groupId = $data['id']; // 根据分组id去寻找订单id,再去寻找点评信息
        // 订单信息
        $oids = Db::name('order_traveler')->where('group_id',$groupId)->column('oid');
        $oids = array_unique($oids);
        $order = Db::name('order')->where('id', 'in', $oids)->field('id,order_id,order_status,title,is_review,booking_people_phone,booking_people_name,platform')->select();
//        dump($order);
        if (!empty($order)){
            foreach ($order as $index => $item) {
                $name = Db::name('platform')->where('platform_name',$item['platform'])->value('name');
                $order[$index]['platform_name'] = empty($name)? $item['platform'] : $name;
                $orderEvaluate = Db::name('order_evaluate')->where('oid',$item['order_id'])->find();
                if (empty($orderEvaluate)){
                    continue;
                }else{
                    $order[$index]['order_evaluate_id'] = $orderEvaluate['id'];
                    $order[$index]['oid'] = $orderEvaluate['oid'];
                    $name = Db::name('platform')->where('platform_name',$orderEvaluate['platform'])->value('name');
                    $order[$index]['platform'] = empty($name)? $orderEvaluate['platform'] : $name;
                    $order[$index]['comment_id'] = $orderEvaluate['comment_id'];
                    $order[$index]['uid'] = $orderEvaluate['uid'];
                    $order[$index]['user_name'] = $orderEvaluate['user_name'];
                    $order[$index]['comment'] = $orderEvaluate['comment'];
                    $order[$index]['shop_name'] = $orderEvaluate['shop_name'];
                    $order[$index]['reply'] = $orderEvaluate['reply'];
                    $order[$index]['comment_status'] = $orderEvaluate['comment_status'];
                    $order[$index]['img_src'] = $orderEvaluate['img_src'];
                    $order[$index]['review'] = $orderEvaluate['review'];
                    $order[$index]['order_evaluate_id'] = $orderEvaluate['id'];
                    $order[$index]['create_time'] = $orderEvaluate['create_time'];
                }
            }
        }
        // 点评列表
        $count = count($order);
        $this->view->assign('count',$count);
        $this->view->assign('order', $order);
        return $this->view->fetch('order_evaluation_details');
    }


    /**
     *  数据导出
     */
    public function export_to_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['ID','司机姓名', '电话', '身份证号', '车牌号', '趟数', '订单总数', '好评数', '差评数', '未评价', '好评率',
            '达标趟数'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li = 0; $li < $li_length; $li++) {
            switch ($letter[$li]) {
                case 'A':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'B':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
                    break;
                case 'C':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'D':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'E':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'F':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'G':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'H':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);
                    break;
                case 'I':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'J':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);
                    break;
                case 'K':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(15);
                    break;
                case 'S':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
                    break;
                case 'T':
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(30);
                    break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
        }
        if ($this::$isdelete){
            $map['d.isdelete'] = 1;
            $map['au.isdelete'] = 1;
        }else{
            $map['d.isdelete'] = 0;
            $map['au.isdelete'] = 0;
        }
        // 司机姓名
        if($data['realname']){
            $map['au.realname'] = ['like',"%{$data['realname']}%"];
        }
        // 司机手机号码
        if($data['mobile']){
            $map['au.mobile'] = ['like',"%{$data['mobile']}%"];
        }
        // 司机身份证
        if($data['id_card']){
            $map['d.id_card'] = ['like',"%{$data['id_card']}%"];
        }
        // 司机车牌号
        if($data['plate_number']){
            $map['d.plate_number'] = ['like',"%{$data['plate_number']}%"];
        }
        // 司机车牌号
        if($data['plate_number']){
            $map['d.plate_number'] = ['like',"%{$data['plate_number']}%"];
        }
        if ($data['title']){
            $driverUserIds = Db::name('dispatch_traveler_group')->where('title','like',"%{$data['title']}%")->column('driver_user_id');
            $driverUserIds = array_unique($driverUserIds); // 获取数组中唯一的用户id
            if (!empty($driverUserIds)){
                $map['au.id'] = ['in', $driverUserIds];
            }
            unset($driverUserIds);
        }
        if ($data['id']){
            $map['d.id'] = ['in', $data['id']];
        }
        // 出发时间
        if (!empty($data['date1']) && !empty($data['date2'])){
            $date = [];
            if ($data['date1'] < $data['date2']){
                $date = [$data['date1'], $data['date2']];
            }else{
                $date = [$data['date2'], $data['date1']];
            }
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date','between time',$date)
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }elseif (!empty($data['date1'])){
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date',strtotime($data['date1']))
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }elseif (!empty($data['date2'])){
            $driverUserIds = Db::name('dispatch_traveler_group')
                ->where('go_date',strtotime($data['date2']))
                ->column('driver_user_id');
            $driverUserIds = empty($driverUserIds)?1:array_unique($driverUserIds); // 获取数组中唯一的用户id
        }
        if (!empty($map['au.id']) && !empty($driverUserIds)){
            foreach ($map['au.id'][1] as $index10 => $item10) {
                if (!in_array($item10,$driverUserIds)){
                    unset($map['au.id'][1][$index10]);
                }
            }
        }elseif(!empty($driverUserIds)){
            if ($driverUserIds == 1){
                $map['au.id'] = 0;
            }else{
                $map['au.id'] = ['in', $driverUserIds];
            }
        }
        $list = Db::name('driver')
            ->alias("d")
            ->join("tp_admin_user au","au.id=d.user_id","left")
            ->where($map)
            ->order('d.id','desc')
            ->field('d.id,au.realname,au.mobile,d.id_card,d.plate_number,d.user_id')
            ->select();
        if ($list){
            foreach ($list as $index => $listDatum) {
                // 根据司机的用户id在分配单里查找已结算的派单
                $dispatchOrder = Db::name('dispatch_traveler_group')
                    ->where('driver_user_id',$listDatum['user_id'])
                    ->where('dispatch_group_status','accounts')
                    ->order('id','desc')
                    ->select();

                $list[$index]['total'] = count($dispatchOrder);
                static $totalOrders = 0; // 总订单数量
                static $totalGoods = 0; // 总好评数量
                static $totalBads = 0; // 总差评数量
                static $totalnotEvaluated = 0; // 总未平价订单
                if ($dispatchOrder){
                    // 获取派单下的总好评数,订单总数,差评数,未评价,好评率
                    foreach ($dispatchOrder as $index01 => $item) {
                        // 普通订单与接送机订单 is_pick_up 为1 时是接送机订单
                        $commonOrder = $this->getCommonOrder($item['id']);
                        $totalGoods += $commonOrder['good'];
                        $totalBads += $commonOrder['bad'];
                        $totalnotEvaluated += $commonOrder['noEvaluation'];
                        $totalOrders += $commonOrder['totalOrder'];
                    }
                }

                if (!empty($totalGoods) || !empty($totalBads) || !empty($totalnotEvaluated)){
                    $feedBack = round($totalGoods/($totalGoods+$totalBads+$totalnotEvaluated)*100, 2);
                } else {
                    $feedBack = 0;
                }
                $list[$index]['totalOrders'] = $totalOrders;
                $list[$index]['totalGoods'] = $totalGoods;
                $list[$index]['totalBads'] = $totalBads;
                $list[$index]['totalnotEvaluated'] = $totalnotEvaluated;
                $list[$index]['feedBack'] = empty($feedBack) ? 0:$feedBack.'%';
                $list[$index]['dabiao'] = Db::name('dispatch_traveler_group')
                                            ->where('driver_user_id',$listDatum['user_id'])
                                            ->where('dispatch_group_status','accounts')
                                            ->where('is_reach_standard',1)
                                            ->order('id','desc')
                                            ->count();
                $totalOrders = 0; // 总订单数量
                $totalGoods = 0; // 总好评数量
                $totalBads = 0; // 总差评数量
                $totalnotEvaluated = 0; // 总未平价订单
            }
        }
        foreach ($list as $lk => $lv) {
            unset($list[$lk]['user_id']);
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "车辆匹配管理-评价管理数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);

        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }
}
